package com.gouaixin.bee.beeframework2.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.util.AbToastUtil;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.bean.USER;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.UpdateListener;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

import static cn.smssdk.framework.utils.R.getStringRes;

/**
 * Created by Administrator on 2015/3/10.
 */
//手机验证界面
public class B17_shoujiYanzhengActivity extends Activity {
    Context context = B17_shoujiYanzhengActivity.this;
    String titleName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.b17_shoujiyanzheng);

        try{

            initSms();



            initIntent();

            initHead();
            initContent();


        }catch (Exception e){
            Log.e("event","错误="+e.getMessage());
        }




    }

    private void initSms() {


//        Intent it=new Intent(context, SmsDemoActivity.class);
//        startActivity(it);
//        //System.loadLibrary("OSbase");
//
//        Log.e("event","000000000000000000000000");
//
//
            SMSSDK.initSDK(this,"732340ec6b34","d03a78efdae0b38ef9e50ccace5d48ac");


//        SMSSDK.initSDK(this, MyConfig.Mob_APPKEY,MyConfig.Mob_APPSECRET);



        Log.e("event","1111111111111111111111");
        EventHandler eh=new EventHandler(){

            @Override
            public void afterEvent(int event, int result, Object data) {
                Log.e("event","44444444444444444444444444");

                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }

        };



        Log.e("event","222222222222222222222");
        SMSSDK.registerEventHandler(eh);



        Log.e("event","33333333333333333333333");


    }

    Handler handler=new Handler(){

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("event", "event=" + event);
            if (result == SMSSDK.RESULT_COMPLETE) {
                //短信注册成功后，返回SmsDemoActivity,然后提示新好友
                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {//提交验证码成功
                    Toast.makeText(getApplicationContext(), "提交验证码成功", Toast.LENGTH_SHORT).show();

                    USER myuser = BmobUser.getCurrentUser(context, USER.class);
                    myuser.setPhone(phonenumber);
                    PreferencesUtils.putString(context, "phone", phonenumber);
                    myuser.update(context, new UpdateListener() {
                        @Override
                        public void onSuccess() {
                            AbToastUtil.showToast(context, "绑定手机成功");
                            finish();
                        }


                        @Override
                        public void onFailure(int i, String s) {

                        }
                    });


                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE){
                    Toast.makeText(getApplicationContext(), "验证码已经发送", Toast.LENGTH_SHORT).show();

                }else if (event ==SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES){//返回支持发送验证码的国家列表
                    Toast.makeText(getApplicationContext(), "获取国家列表成功", Toast.LENGTH_SHORT).show();


                }
            } else {
                ((Throwable) data).printStackTrace();
                int resId = getStringRes(context, "smssdk_network_error");
                Toast.makeText(context, "验证码错误", Toast.LENGTH_SHORT).show();
                if (resId > 0) {
                    Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
                }
            }

        }

    };


    /***
     * 获取传送过来的Intent对象
     */
    private void initIntent() {

        Intent it=getIntent();
        titleName=it.getStringExtra("title");
    }


    /**
     * 内容区域的监听
     */
    String phonenumber = "";
    String codenumber = "";
    EditText phone;
    EditText code;
    TextView huoqu;
    TextView queding;

    private void initContent() {
        phone = (EditText) findViewById(R.id.phone);
        code = (EditText) findViewById(R.id.code);
        huoqu = (TextView) findViewById(R.id.huoqu);
        queding= (TextView) findViewById(R.id.queding);

        huoqu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phonenumber = phone.getText().toString();
                android.util.Log.e("Main", "点击发送验证码:");
                if(!isMobile(phonenumber)){
                    Toast.makeText(context,"请输入正确的手机号码",Toast.LENGTH_SHORT).show();
                    return;
                }else{
//                    sendsms(phonenumber);

                    SMSSDK.getVerificationCode("86", phonenumber);//发送手机验证码

                    time = new TimeCount(60000, 1000);
                    time.start();
                }

            }
        });

        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phonenumber = phone.getText().toString();
                codenumber = code.getText().toString();
                android.util.Log.e("Main", "点击验证手机号:");

                SMSSDK.submitVerificationCode("86", phonenumber, codenumber);





//                if(codenumber.equals(""+mobile_code)){
//                    mLogUtil.e("执行验证手机方法");
//                    USER myuser = BmobUser.getCurrentUser(context, USER.class);
//                    myuser.setPhone(phonenumber);
//                    myuser.update(context, new UpdateListener() {
//                        @Override
//                        public void onSuccess() {
//                            AbToastUtil.showToast(context, "绑定手机成功");
//                            finish();
//                        }
//
//
//                        @Override
//                        public void onFailure(int i, String s) {
//
//                        }
//                    });
//
//
//                }else{
//                    AbToastUtil.showToast(context,"您输入的验证码有误，请重新输入");
//                }


            }
        });





    }


    //获取验证码
    private void onGetCode(String phone) {

        if(!TextUtils.isEmpty(phone)){
            SMSSDK.getVerificationCode("86", phone);
        }else {
            Toast.makeText(this, "电话不能为空", Toast.LENGTH_SHORT).show();
        }

    }






    TimeCount time;

    int mobile_code;

    private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";//短信服务后台

    String content;

    private void sendsms(String phonenumber) {
        mobile_code= (int) ((Math.random() * 9 + 1) * 100000);
        content= new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。");

        RequestParams params = new RequestParams();

        params.addBodyParameter("account", "cf_qutian");
        params.addBodyParameter("password", "123456");
        params.addBodyParameter("mobile", phonenumber);
        params.addBodyParameter("content", content);

        mLog.e("params:" + params);

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                Url,
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        mLog.e("获取验证码：开始" + "conn...");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            mLog.e("获取验证码：正在加载" + "upload: " + current + "/" + total);
                        } else {
                            mLog.e("获取验证码：正在加载" + "reply: " + current + "/" + total);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mLog.e("获取验证码：成功" + "reply: " + responseInfo.result);

                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mLog.e("获取验证码：失败" + error.getExceptionCode() + ":" + msg);
                    }
                }
        );
    }

    /**
     * 头部的监听
     */
    private void initHead() {
        //顶部
        ImageView back;//返回
        TextView title;//标题

        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.title);

        title.setText(titleName);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            huoqu.setBackgroundColor(Color.parseColor("#B6B7B6"));
            huoqu.setClickable(false);
            huoqu.setText(millisUntilFinished / 1000 + "秒后可重新发送");
        }

        @Override
        public void onFinish() {
            huoqu.setText("免费获取验证码");
            huoqu.setClickable(true);
            huoqu.setBackgroundColor(Color.parseColor("#FD6B8F"));
        }
    }

    //验证手机格式
    public static boolean isMobile(String mobiles) {
//        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        String telRegex = "[1]\\d{10}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }

}
